import { ref } from 'vue'

interface Toast {
  id: number
  type: 'success' | 'error' | 'warning' | 'info'
  message: string
}

const toasts = ref<Toast[]>([])
let nextId = 1

export const useToast = () => {
  const show = (type: Toast['type'], message: string, duration = 3000) => {
    const id = nextId++
    const toast: Toast = {
      id,
      type,
      message,
    }
    toasts.value.push(toast)

    setTimeout(() => {
      const index = toasts.value.findIndex(t => t.id === id)
      if (index > -1) {
        toasts.value.splice(index, 1)
      }
    }, duration)
  }

  const success = (message: string, duration?: number) => show('success', message, duration)
  const error = (message: string, duration?: number) => show('error', message, duration)
  const warning = (message: string, duration?: number) => show('warning', message, duration)
  const info = (message: string, duration?: number) => show('info', message, duration)

  return {
    toasts,
    success,
    error,
    warning,
    info,
  }
}
